package com.yance.fim.handler;

import com.yance.fim.core.enums.Command;
import com.yance.fim.core.packets.FimPacket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;

/**
 * IM消息处理器
 * 主要用户用户私聊、群聊等操作
 *
 * @author yance
 */
@Service
public class ImMessageHandler implements BaseMessageHandler {

    private static final Logger logger = LoggerFactory.getLogger(ImMessageHandler.class);

    @Autowired
    private PushMessageHandler pushMessageHandler;

    @Override
    public void handler(FimPacket fimPacket, ChannelContext channelContext) {
        Command command = fimPacket.getHeader().getCommand();
        if (command == Command.SEND) {
            pushMessageHandler.receiveSendMessage(fimPacket, channelContext);
        } else {
            logger.error("Unkonwn Command:{}", command);
            errorCommand(channelContext);
        }
    }

    /**
     * 处理未知指令，关闭当前连接
     *
     * @param channelContext
     */
    private void errorCommand(ChannelContext channelContext) {
        Tio.close(channelContext, "Unkonwn Command");
    }
}
